<template>
    <div
        class="to-sap-dialog"
        v-if="toSapDialogShow"
        v-show="toSapList.length > 0"
    >
        <ul class="to-sap-detail" ref="toSapRef">
            <li v-for="(item, index) in toSapList">
                <!-- <span style="margin-right: 5px"
                    ><el-checkbox
                        :key="index"
                        v-model="item.checked"
                        @change="changeHandle(item)"
                /></span> -->
                <span>{{ formatDate(item.CreatedAt, "hh:mm:ss") }}</span>
                <!-- <span style="margin-right: 7px">{{ item.step }}</span> -->
                <span style="margin-left: 7px">{{ item.operation }}</span>
            </li>
        </ul>
        <span class="close-icon" @click="toSapDialogShow = false">关闭</span>
        <!-- <span class="upload-icon" @click="exportToSapLogExportFun">下载</span> -->
    </div>
    <!-- <el-dialog v-model="toSapDialogShow" title="汇入sap" width="1000">
        <div>款式编号：{{ formData.styleNum }}</div>
        <el-table
            :data="toSapList"
            @selection-change="handleSelectionChange"
            style="width: 100%"
            :maxHeight="'500px'"
            row-key="ID"
            border
        >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="step" label="步骤" width="70">
            </el-table-column>
            <el-table-column prop="operation" label="内容"> </el-table-column>
        </el-table>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="exportToSapLogExportFun">下载</el-button>
            </div>
        </template>
    </el-dialog> -->
</template>

<script setup>
defineOptions({
    name: "toSap",
});
import { ElLoading } from "element-plus";
import {
    onMounted,
    reactive,
    toRefs,
    ref,
    defineExpose,
    defineProps,
    onBeforeUnmount,
    defineEmits
} from "vue";
import { useRoute, useRouter } from "vue-router";
import {
    getProductStylesList,
    exportToSapLog,
    exportToSap2,
    exportToSapLogExport,
} from "@/api/plmProductStyles";
import { findProductSpec } from "@/api/plmProductSpec";
import { emitter } from "@/utils/bus.js";
import { getDict } from "@/utils/dictionary";
import { ElMessage, ElMessageBox } from "element-plus";
import { formatDate } from "@/utils/format";
const route = useRoute();
const router = useRouter();

const emits = defineEmits(["reloadPageFun"])
const props = defineProps({
    formData: {
        type: Object,
        default: {},
    },
    type: {
        type: String,
        default: "",
    },
    ID: {
        type: String,
        default: "",
    },
});

const toSapDialogShow = ref(false);
const num = ref(0);
const toSapList = ref([]);

const apiExoprt = ref({
    largeScaleOrder: "/largeScaleOrder/exportToSap",
    masterBOM: "/masterBOM/exportToSap",
});
const apiLog = ref({
    largeScaleOrder: "/largeScaleOrder/exportToSapStepLog",
    masterBOM: "/masterBOM/exportToSapStepLog",
});
const apiUpload = ref({
    largeScaleOrder: "/largeScaleOrder/exportToSapLogExport",
    masterBOM: "/masterBOM/exportToSapLogExport",
});

const toSapRef = ref();

const toSapRefFun = () => {
    if (toSapRef.value) {
        toSapRef.value.scrollTop = toSapRef.value.scrollHeight;
    }
};

const tableLog = ref([]);

const seleRow = ref([]);
const handleSelectionChange = (val) => {
    seleRow.value = val;
};

// 后端路径
const path1 = ref(import.meta.env.VITE_BASE_API + "/");

const changeHandle = (val) => {
    if (val.checked) {
        seleRow.value.push(val.step);
    } else {
        let index = seleRow.value.findIndex((res) => {
            return res == val.step;
        });
        if (index != -1) {
            seleRow.value.splice(index, 1);
        }
    }
    seleRow.value = Array.from(new Set(seleRow.value));
};

// 导出日志
const exportToSapLogExportFun = () => {
    let l = Array.from(new Set(seleRow.value));
    let ida = route.query.ID || props.formData.ID;
    exportToSapLogExport(
        {
            ID: ida,
            steps: l.join(","),
        },
        apiUpload.value[props.type]
    ).then((res) => {
        const fileUrl = path1.value + res.data.fileUrl;
        const link = document.createElement("a");
        link.href = fileUrl;
        let name =
            res.data.fileUrl.split("/")[res.data.fileUrl.split("/").length - 1];
        link.setAttribute("download", name);
        link.click();
    });
};

const loadingInstance = ref();
var clickTime = Date.now();
const toSapLoading = ref(false);
function toSap() {
    seleRow.value = [];
    toSapList.value = [];
    let ida = route.query.ID || props.formData.ID;
    if (!ida) return;
    toSapDialogShow.value = true;
    // 显示全屏锁定
    loadingInstance.value = ElLoading.service({
        lock: true,
        text: "正在汇入SAP",
        background: "rgba(0, 0, 0, 0.1)",
    });

    let date = new Date().getTime();
    num.value = 0;
    toSapList.value = [];
    let taskId = Math.floor(Math.random() * 10000000)
    toSapLoading.value = true
    exportToSap2({ ID: ida, taskId:taskId }, apiExoprt.value[props.type])
        .then((res) => {
            loadingInstance.value.close();
            if(res.code != 0){
                toSapLoading.value = false
            }
        })
        .catch((err) => {
            loadingInstance.value.close();
            toSapLoading.value = false
        });
    setTimeout(() => {
        clickTime = Date.now();
        getLog(date,taskId);
    }, 2000);
}
// 获取日志
function getLog(date,taskId) {
    let ida = route.query.ID || props.formData.ID;
    exportToSapLog({ ID: ida, taskId:taskId }, apiLog.value[props.type])
        .then((res) => {
            if (res.code == 0) {
                toSapList.value = res.data.list;
                num.value += 1;
                // 滚动
                setTimeout(() => {
                    toSapRefFun();
                }, 400);

                if (
                    toSapList.value.length > 0 &&
                    toSapList.value[toSapList.value.length - 1].status == 0
                ) {
                    // toSapDialogShow.value = false
                    let str =
                        toSapList.value[toSapList.value.length - 1].operation;
                    let date = formatDate(
                        toSapList.value[toSapList.value.length - 1].CreatedAt,
                        "hh:mm:ss"
                    );
                    // loadingInstance.value.close();
                    ElMessageBox.alert(`（${date}）${str}`, {
                        confirmButtonText: "取消",
                    });
                    return;
                }
                if (
                    toSapList.value.length > 0 &&
                    toSapList.value[toSapList.value.length - 1].status == 2
                ) {
                    // loadingInstance.value.close();
                    ElMessage({
                        type: "success",
                        message: `汇入SAP成功`,
                        duration: 5000,
                    });
                    emitter.emit("reload");
                    emits('reloadPageFun')
                    // toSapDialogShow.value = false;
                    return;
                }

                setTimeout(() => {
                    let flag = 1;
                    if (toSapList.value.length > 0) {
                        // status 1:正常；0：错误；2：汇入成功；
                        flag =
                            toSapList.value[toSapList.value.length - 1].status;
                        if (toSapDialogShow.value && flag == 1 && toSapLoading.value) {
                            getLog(date, taskId);
                        }
                    } else if(toSapLoading.value){
                        let stopTime = Date.now()
                        if((stopTime - clickTime)  /1000 < 10){
                            getLog(date, taskId);
                        }
                    }
                }, 800);
            }
        })
        .catch((err) => {
            loadingInstance.value.close();
        });
}

defineExpose({ toSapDialogShow, getLog, toSap });

onMounted(() => {
    setTimeout(() => {
        toSapRefFun();
    }, 2000);
});
onBeforeUnmount(() => {
    toSapDialogShow.value = false;
});
</script>

<style lang="scss" scoped>
.to-sap-dialog {
    position: absolute;
    left: 0;
    bottom: 0;
    z-index: 2;
    min-width: 200px;
    max-width: 900px;
    .to-sap-detail {
        background: rgba(211, 233, 254, 0.4);
        box-shadow: 5px 25px 20px 55px rgba(211, 233, 254, 0.4);
        margin-left: 10px;
        & > li {
            list-style-type: disc;
            margin-left: 8px;
            display: flex;
            width: auto;
            word-break: keep-all;
            white-space: nowrap;
            margin-bottom: 6px;
            font-size: 16px;
            font-weight: 600;
            align-items: center;
        }
        padding: 10px;
        max-height: 400px;
        overflow: scroll;
        :deep(.el-checkbox) {
            height: auto;
        }
        &::-webkit-scrollbar {
            display: none;
        }
    }
    .close-icon {
        position: absolute;
        top: -15px;
        right: -30px;
        cursor: pointer;
        color: #fff;
        background: #4d70ff;
        padding: 6px 10px;
        font-size: 16px;
        font-weight: 900;
        border-radius: 10px;
        // color: red;
        // background: #4d70ff;
        // padding: 2px 6px;
        // border-radius: 8px;
        // color: #fff;
    }
    .upload-icon {
        position: absolute;
        top: -10px;
        right: 10px;
        cursor: pointer;
        // color: red;
        // background: #4d70ff;
        // padding: 2px 6px;
        // border-radius: 8px;
        // color: #fff;
    }
}
</style>